#!/usr/bin/env python

import os, sys, shutil, zipfile
from optparse import OptionParser

op = OptionParser ()
op.add_option ( "-p", "--path", dest = "path", help = "Set the site destination path", metavar = "PATH", default = '.' )
op.add_option ( "-n", "--name", dest = "name", help = "Set the site name to NAME", metavar = "NAME" )
op.add_option ( "-l", "--liwe", dest = "liwe", help = "Set the liwe sources directory", metavar = "LIWE" )
op.add_option ( "-c", "--copy", dest = "copy", help = "Copy standard files instead of simply symlink them [MANDATORY ON Windows]", default = False, action = 'store_true' )
op.add_option ( "-f", "--full", action = "store_true", dest = "full", help = "Create the full LiWE WebSite file structure", default = False )

( options, args ) = op.parse_args ()

dct = eval ( str ( options ) )

if not dct.get ( "liwe" ):
	sys.stderr.write ( "\nERROR: you MUST specify the --liwe parameter.\n" )
	sys.exit ( 1 )

if not dct.get ( "name" ):
	sys.stderr.write ( "\nERROR: you MUST specify the --name parameter.\n" )
	sys.exit ( 1 )

liwe_site_base = os.path.join ( dct [ 'liwe' ], 'tools', 'data', 'liwe_site_base.zip' )
if not os.path.isfile ( liwe_site_base ):
	sys.stderr.write ( "\nERROR: could not find %s. Maybe the --liwe parameter specified is invalid.\n" % liwe_site_base )
	sys.exit ( 1 )
	

dest_path = os.path.join ( dct [ 'path' ], dct [ 'name' ] )

# Solo se full == True
if os.path.isdir ( dest_path ): shutil.rmtree ( dest_path )


os.mkdir ( dest_path )
zfile = zipfile.ZipFile ( liwe_site_base, mode = 'r' )
zfile.extractall ( dest_path )
zfile.close ()

def mk_symlink ( dest_dir, old_fname, new_path, new_fname, copy = True ):
	# Cancello il vecchio file ".lnk"
	old_filename = os.path.join ( dest_dir, old_fname )
	os.unlink ( old_filename )

	# Creo il path del file nuovo da linkare
	new_filename = os.path.join ( new_path, new_fname )
	dest_filename = os.path.join ( dest_dir, new_fname )

	# Se devo copiare
	if copy:
		shutil.copytree ( new_filename, dest_filename )
	else:
		os.symlink ( new_filename, dest_filename )

def sub_stubs ( arg, dirname, fnames ):
	for fil in fnames:
		if fil.endswith ( ".lnk" ):
			dest_name = fil [ : -4 ]
			add_dir = os.path.basename ( dirname.replace ( dest_path, "" ) )
			if add_dir == 'web': add_dir = ''
			"""
			print add_dir
			if fil == 'os3jslib.lnk':
				mk_symlink ( dirname, fil, dct [ 'liwe' ], dest_name  )
			elif fil == 'os3wwl.lnk':
				mk_symlink ( dirname, fil, dct [ 'liwe' ], dest_name )
			else:
			"""
			mk_symlink ( dirname, fil, os.path.join ( dct [ 'liwe' ], add_dir ), dest_name, dct [ 'copy' ] )

os.path.walk ( dest_path, sub_stubs, dct )
